<?php
/**
 * Created by PhpStorm.
 * User: huqi
 * Date: 2019-12-29
 * Time: 01:46
 */

namespace WebUtil\Matrix;

class CsvExport
{
    public  $header = [];
    private $filename;
    private $handle = null;
    private $isPutHeader = false;
    private $tf;

    /**
     * @param array $header
     * @param $filename
     * @return CsvExport
     */
    public static function instance(array $header , $filename)
    {
        return new static($header,$filename);
    }

    public function __construct(array $header , $filename)
    {
        $this->header = $header;
        $this->filename = $filename;
    }

    public function putMulti(array $fields)
    {
        if ($this->handle == null){
            $this->handle = fopen($this->filename,'a+');
        }
        foreach ($fields as $field){
            $this->put($field);
        }
    }

    public function close(){
        if ($this->handle !== null) {
            fclose($this->handle);
        }
    }

    private function put(array $field)
    {
        if (!$this->isPutHeader){
            fputcsv($this->handle , array_values($this->header));
            $this->isPutHeader = true;
        }
        if ($this->tf){
            $field = call_user_func($this->tf,$field);
        }
        fputcsv($this->handle , $field);
    }

    public function transform($input){
        $this->putMulti($input);
        $this->close();
    }

    public function setTransform(\Closure $tf)
    {
        $this->tf = $tf;
    }
}